package com.sinosoft.ptas.system.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sinosoft.framework.core.api.domain.PmsData;
import com.sinosoft.framework.core.api.domain.ResourceEntity;
import com.sinosoft.framework.core.api.domain.RoleEntity;
import com.sinosoft.framework.core.api.service.ResourceService;
import com.sinosoft.framework.core.api.service.UserService;
import com.sinosoft.ptas.system.commom.PtasConstant;
import com.sinosoft.ptas.system.security.SecurityUtil;

@Controller
@RequestMapping("/")
public class LoginController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	ResourceService resourceService;

	/**
	 * 登录页面
	 * @return
	 */
	@RequestMapping(value="login", method = RequestMethod.GET)
	public String login() {
		if(SecurityUtil.isLogin()) {
			return "redirect:/";
		}
		return "main/login";
	}
	
	/*
	 * 
	 */
	@RequestMapping(value="login", method = RequestMethod.POST)
	public String fail(HttpServletRequest req, @RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
        String errorMsg = null;
        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
        	errorMsg = "用户名不存在或用户名已失效";
        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
        	errorMsg = "密码错误";
        } else if(exceptionClassName != null) {
        	errorMsg = "其他错误：" + exceptionClassName;
        }
        model.addAttribute("errorMsg", errorMsg);
       // 此方法不处理登陆成功（认证成功），shiro认证成功会自动跳转到上一个请求路径
       // 登陆失败还到login页面
        return "main/login";
	}
	
	/**
	 * 系统默认页面
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String main(Model model) {
		model.addAttribute(PtasConstant.system_username, SecurityUtil.getUsername());
		this.initAppContext(SecurityUtil.getUsername(), SecurityUtil.getCurrentSession());	//	加载应用上下文
		return "main/index";
	}
	
	/**
	 * 退出页面
	 * @return
	 */
	@RequestMapping(value="logout", method = RequestMethod.POST)
	@ResponseBody
	public String logout() {
		
		Subject subject = SecurityUtils.getSubject();
		if(subject.isAuthenticated()){
			subject.logout();
		}
		return "success";
	}
	
	private void initAppContext(String username, Session session) {
		String aid = PtasConstant.system_aid;
		PmsData pmsData=userService.getPmsData(aid, username);
		List<RoleEntity> roleEntitys = pmsData.getRoleEntitys();
		session.setAttribute(PtasConstant.pms_role, roleEntitys);
		String oid = pmsData.getOid();
		session.setAttribute(PtasConstant.pms_orgnization, oid);
		session.setAttribute(PtasConstant.pms_app_content, pmsData);
	}
}
